package com.dems.admin.config;

import com.dems.core.log.TraceIdContext;
import com.dems.core.log.TraceIdUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class TraceIdFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;

        HttpServletResponse response = (HttpServletResponse) res;

        String requestId = request.getHeader(TraceIdContext.TRACE_ID_PREFIX + TraceIdContext.TRACE_ID_KEY);

        if (StringUtils.isBlank(requestId)) {
            requestId = request.getHeader(TraceIdContext.EAGLE_ID_KEY);
        }

        if (StringUtils.isEmpty(requestId)) {
            requestId = TraceIdUtils.getTraceId();
        }
        TraceIdContext.setTraceId(requestId);
        response.addHeader(TraceIdContext.TRACE_ID_PREFIX + TraceIdContext.TRACE_ID_KEY, requestId);

        chain.doFilter(req, res);
    }

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void destroy() {
        // 调用结束后删除
        TraceIdContext.removeTraceId();
    }

}
